﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CWD.DAL;

namespace CWD
{
    public partial class fmTabPrint : Form
    {
        public SqlConnection conn;
        public string username;
        public int AllotDID=-1;
        public int MoDID = -1;
        public fmTabPrint()
        {
            InitializeComponent();
        }

        private void tbModid_TextChanged(object sender, EventArgs e)
        {
            if (tbModid.Text.Trim().Length >= 5)
            {
                GetMoDesc();
            }
        }
        private string ValidData(int modid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" select isnull(mos.closeuser,'') closeuser,qty,qty-isnull(QualifiedInQty,0) unfinish  from  mom_order mo left join mom_orderdetail mos on mo.moid=mos.moid where modid=" + modid);
            DataTable dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            if (dt.Rows.Count == 0)
                return "找不到这个生产订单！";
            if (dt.Rows[0]["closeuser"].ToString() != "")
                return "当前订单已经关闭！";
            if (Common.GetInt(dt.Rows[0]["unfinish"])<=0)
                return "当前订单已经完工！";
            return "";
        }
        private void GetMoDesc()
        {
            MoDID = Common.GetInt(tbModid.Text.Trim());
            string Msg=ValidData(MoDID);
            if (Msg != "")
            {
                Common.ShowMessage(Msg, 2);
                return;
            }
            ctQty.Text = "";
            ctTabqty.Text = "";
            StringBuilder sb=new StringBuilder();            
            string MoDesc="";
            sb.Append(@" select  mocode+'_'+cast(sortseq as varchar(2)) as Mocode,isnull(ccusabbname,'') ccusabbname,
                invcode,inv.cinvname,cinvstd,cast(qty as numeric(10,1)) qty,ccomunitname,
                cast(isnull(QualifiedInQty,0) as numeric(10,1))  qualifiedInQty from mom_order mo 
                left join mom_orderdetail mos on mo.moid=mos.moid left join so_sodetails sos on mos.orderdid=sos.isosid 
                left join so_somain so on sos.id=so.id left join customer on so.cCuscode=customer.cCuscode 
                left join inventory inv on mos.invcode=inv.cinvcode 
                left join computationunit unit on inv.ccomunitcode=unit.ccomunitcode 
                where mos.modid=" + tbModid.Text.Trim());
            DataTable dt=SqlAccess.ExecuteSqlDataTable(sb.ToString(),conn);
            string Mocode = dt.Rows[0]["mocode"].ToString().Trim();
            tbMocode.Text = Mocode;
            if(dt.Rows[0]["ccusabbname"].ToString()!="")
                MoDesc="由"+dt.Rows[0]["ccusabbname"].ToString().Trim()+"订制，";
            MoDesc+=dt.Rows[0]["invcode"].ToString().Trim()+dt.Rows[0]["cinvname"].ToString().Trim()+dt.Rows[0]["cinvstd"].ToString().Trim();
            MoDesc+=" 数量"+dt.Rows[0]["qty"].ToString().Trim()+dt.Rows[0]["ccomunitname"].ToString().Trim();       
            if(Common.GetNum(dt.Rows[0]["QualifiedInQty"])>0)
                MoDesc+="，已完成"+Common.GetNum(dt.Rows[0]["QualifiedInQty"]).ToString()+dt.Rows[0]["ccomunitname"].ToString().Trim();
            MoDesc += " 使用原料：";
            decimal MoQty = Common.GetInt(dt.Rows[0]["qty"]);
            sb.Remove(0, sb.Length);
            sb.Append(" select invcode,cinvname,cinvstd,cast(qty as numeric(10,1)) qty,ccomunitname,cast(isnull(issqty,0) as numeric(10,1)) issqty from mom_moallocate allo left join inventory inv on allo.invcode=inv.cinvcode left join computationunit unit on inv.ccomunitcode=unit.ccomunitcode where allo.modid=" + tbModid.Text.Trim());
            dt.Clear();
            dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            for (int i = 0; i < dt.Rows.Count; i++)
            { 
                 MoDesc+="\n"+dt.Rows[0]["invcode"].ToString().Trim()+dt.Rows[0]["cinvname"].ToString().Trim()+dt.Rows[0]["cinvstd"].ToString().Trim()+"应领"+dt.Rows[0]["qty"].ToString().Trim()+dt.Rows[0]["ccomunitname"].ToString().Trim(); 
                MoDesc+="已领"+dt.Rows[0]["issqty"].ToString().Trim()+dt.Rows[0]["ccomunitname"].ToString().Trim(); 
            }
            
            dt.Clear();
            sb.Remove(0,sb.Length);
            sb.Append(@" select sum(Num*Packets) num,sum(Packets) Packets 
                    from ekk..c_PacketsTab pack 
                    where pack.Modid=" +MoDID );
            dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            if (Common.GetInt(dt.Rows[0]["Num"]) > 0)
            {
                MoDesc += "已打印 条数:" + dt.Rows[0]["Num"].ToString() + ",包数 " + dt.Rows[0]["Packets"].ToString() + "。";
            }
            ctLeft.Text =String.Format("{0:0}", MoQty - Common.GetInt(dt.Rows[0]["Num"]));
            tbMemo.Text=MoDesc;
             
             ctQty.Text =Common.GetNum(dgvAllot.Rows[dgvAllot.CurrentCell.RowIndex].Cells["数量"].Value).ToString();
              int SetNum=Common.GetInt(SqlAccess.ExecuteScalar(" select eachpacketnum from ekk..c_prodpacketset pset left join inventory inv on pset.cinvccode=inv.cinvccode left join mom_orderdetail mos on inv.cinvcode=mos.invcode where modid="+ tbModid.Text.Trim(),conn));
              if (SetNum > 0)
              {
                  int packetnum = Common.GetInt(ctQty.Text) % SetNum > 0 ? Common.GetInt(ctQty.Text) / SetNum + 1 : Common.GetInt(ctQty.Text) / SetNum;
                  ctTabqty.Text = packetnum.ToString();
                  ctSetnum.Text = SetNum.ToString();
              }
        }

        private void fmTabPrint_Load(object sender, EventArgs e)
        {
            if (conn == null)
            {
                Common.ShowMessage("未传入连接，不能载入数据！", 2);
                return;
            }
            if (conn.State.ToString().ToLower() != "open")
                conn.Open();
            StringBuilder sb = new StringBuilder();
            sb.Append("select top 200 sheetid from ekk..c_mateallot order by dDate desc");
            DataTable dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            cbAllot.DataSource = dt;
            cbAllot.DisplayMember = "sheetid";
            ctUser.Text = username;
            dgvAllot.AutoGenerateColumns = false;
            dgvAllot.ReadOnly = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void tbModid_Click(object sender, EventArgs e)
        {
            InputNum input = new InputNum();
            if (input.ShowDialog() != DialogResult.OK)
                return;

            tbModid.Text = input.cResult;
            if (input.cResult.Length >= 5)
            {
                GetMoDesc();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (MoDID==-1)
            {
                MessageBox.Show("未找到生产订单号，不能打印！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }
            string msg = CheckData(MoDID);
            if (msg != "")
            {
                Common.ShowMessage(msg, 2);
                return;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("select max(autoid) from ekk..c_PacketsTab pack where pack.Modid=" + MoDID);
            int MaxID = Common.GetInt(SqlAccess.ExecuteScalar(sb.ToString(), conn));
            sb.Remove(0, sb.Length);
            if (!ckPrintbefore.Checked)
            {
                if (!SaveData(MoDID))
                    return;

                sb.Append(@"select AutoID,mocode+'_'+cast(sortseq as varchar(2)) mocode
                    from ekk..c_PacketsTab pack 
                    left join Mom_orderdetail mos on pack.modid=mos.modid
                    left join Mom_order mo on mos.moid=mo.moid
                    where pack.Modid=" + MoDID);
                if (MaxID > 0)
                    sb.Append(" and autoid >" + MaxID);
                if (tbColor.Text.Trim() != "")
                    sb.Append(" and Color=" + tbColor.Text);
            }
            else
                sb.Append(@"select AutoID,mocode+'_'+cast(sortseq as varchar(2)) mocode
                    from ekk..c_PacketsTab pack 
                    left join Mom_orderdetail mos on pack.modid=mos.modid
                    left join Mom_order mo on mos.moid=mo.moid
                    where pack.Modid=" + MoDID);
            DataTable dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            dbBed ds = new dbBed();
            ds.Tables["dtTab"].Clear();
            int sum = 0;
            int qty = Common.GetInt(ctQty.Text);
            for (int i = 0; i < dt.Rows.Count; i++)
            {       
                    int tabid = Common.GetInt(dt.Rows[i]["autoid"]);
                    string mocode=dt.Rows[i]["mocode"].ToString();
                    C_PacketsTab packet = new C_PacketsTab(tabid, conn);                    
                    
                    DataRow dr = ds.Tables["dtTab"].NewRow();
                    dr["AutoID"] =String.Format("*{0:000000}*",packet.PackCode);
                    dr["MoDID"] = MoDID;
                    dr["mocode"] = mocode;
                    dr["cInvcode"] = packet.Mos.InvCode;
                    dr["cInvname"] = packet.Mos.InvName;
                    dr["cInvstd"] = packet.Mos.InvStd;
                    dr["num"] = packet.Num;
                    dr["allQty"] =packet.Mos.Qty;
                    dr["CusAbbName"] = packet.CusName;
                    if(packet.Color!="")
                        dr["Color"]="色号:"+packet.Color;
                    dr["comunitname"] =packet.Mos.ComUnitName;
                    ds.Tables["dtTab"].Rows.Add(dr);
                    sum +=(int) packet.Num;
                    if (sum >= qty)
                        break;
                }
                if (ds.Tables["dtTab"].Rows.Count < 1)
                {
                    MessageBox.Show("没有数据！", "提示");
                    return;
                }
                fmReport rep = new fmReport();
                crtBarTab crt = new crtBarTab();
                crt.SetDataSource(ds);

                crt.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Landscape;
                rep.crystalReportViewer1.ReportSource = crt;

                rep.ShowDialog();
        }

        private string GetPackCode(SqlConnection conn)
        {
            string Code = "";
            string HostName = "";
            HostName = System.Net.Dns.GetHostName().ToString().Trim();
            //HostName = "床品裁剪1.";
            int sortseq = Common.GetInt(HostName.Replace("床品裁剪", "").Replace(".",""));
            
            StringBuilder sb = new StringBuilder();
            sb.Append(" select max(PackCode) from ekk..c_PacketsTab where len(Packcode)=6 and substring(Packcode,1,1)='" + sortseq + "'");
            Code = SqlAccess.ExecuteScalar(sb.ToString(), conn).ToString();
            if (Code == "")
                Code = "000000";
            Code = String.Format("{0}{1:00000}", sortseq, Common.GetInt(Code.Substring(1, 5)) + 1);
            return Code;
        }
        private Boolean SaveData(int modid)
        {
            StringBuilder sb=new StringBuilder();
            int SetNum = Common.GetInt(ctSetnum.Text);
            if (SetNum == 0)
            {
                Common.ShowMessage("未设置此类存货的每包装条数，不能打印标签！", 2);
                return false;
            }            
            int Qty = Common.GetInt(ctQty.Text);
            sb.Remove(0, sb.Length);
            decimal MoQty = 0;
            sb.Append(" select qty from mom_orderdetail where modid=" + modid);
            MoQty = Common.GetNum(SqlAccess.ExecuteScalar(sb.ToString(), conn));
            sb.Remove(0, sb.Length);
            sb.Append("select sum(Packets*Num) qty from ekk..c_PacketsTab where Modid=" + modid);
            decimal printqty = Common.GetNum(SqlAccess.ExecuteScalar(sb.ToString(), conn));
            sb.Remove(0, sb.Length);
            sb.Append(@"select cCusAbbName from Customer cus left join So_somain so on cus.ccuscode=so.ccuscode 
            left join so_sodetails sos on so.id=sos.id left join mom_orderdetail mos on mos.orderdid=sos.isosid where mos.modid=" + modid);
            object oj=SqlAccess.ExecuteScalar(sb.ToString(), conn);
            string cusabbname=oj==null?"":oj.ToString();
            List<C_PacketsTab> Packets = new List<C_PacketsTab>();
            string PacketCode = "";
            if (MoQty- printqty >= Qty )
            {                
                for (int i = 0; i < Common.GetInt(Qty / SetNum); i++)
                {
                    C_PacketsTab packet = new C_PacketsTab();
                    packet.Packets = 1;
                    packet.MoDID = modid;
                    packet.Num = SetNum;
                    packet.bPrint = true;
                    packet.Color = tbColor.Text;
                    packet.CusName = cusabbname;
                    if (PacketCode == "")
                    {
                        packet.PackCode = GetPackCode(conn);
                        PacketCode = packet.PackCode;
                    }
                    else
                    {
                        packet.PackCode = String.Format("{0}{1:00000}", PacketCode.Substring(0, 1), Common.GetInt(PacketCode.Substring(1, 5)) + 1);
                        PacketCode = packet.PackCode;
                    }
                    Packets.Add(packet);                    
                }
                if (Qty%SetNum > 0)
                {
                    C_PacketsTab packet1 = new C_PacketsTab();
                    packet1.Packets = 1;
                    packet1.MoDID = modid;
                    packet1.Num = Qty - Common.GetInt(Qty / SetNum)*SetNum;
                    //packet1.AllotDID = allotdid;
                    packet1.bPrint = true;
                    packet1.Color = tbColor.Text;
                    packet1.CusName = cusabbname;
                    if (PacketCode == "")
                    {
                        packet1.PackCode = GetPackCode(conn);
                        PacketCode = packet1.PackCode;
                    }
                    else
                    {
                        packet1.PackCode = String.Format("{0}{1:00000}", PacketCode.Substring(0, 1), Common.GetInt(PacketCode.Substring(1, 5)) + 1);
                        PacketCode = packet1.PackCode;
                    }
                    Packets.Add(packet1);                    
                }
                SqlTransaction tran = conn.BeginTransaction();
                 try
                 {
                    for (int i = 0; i < Packets.Count; i++)
                    {                   
                        Packets[i].Add(tran);                     
                    }
                    tran.Commit();
                 }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Common.ShowMessage(ex.Message, 2);
                    return false;
                }
                return true;
            }            
            return false;
        }
        private string CheckData(int modid)
        {
            StringBuilder sb = new StringBuilder();
            int moqty = Common.GetInt(SqlAccess.ExecuteScalar("select qty from mom_orderdetail where modid=" + modid, conn));
            int qty = Common.GetInt(ctQty.Text);
            if (qty <= 0)
            {
                return "标签打印数量不得小于零！";
            }
            sb.Append("select sum(Packets*Num) qty from ekk..c_PacketsTab where Modid=" + modid);
            decimal printqty = Common.GetNum(SqlAccess.ExecuteScalar(sb.ToString(), conn));
            if (moqty - printqty > 0 && ckPrintbefore.Checked)
            {
                return "当前订单仍有未打印标签，不能打印以前标签！";
            }
            if (moqty - printqty <qty && !ckPrintbefore.Checked)
            {
                return "当前订单未打印标签少于指定打印数量，不能打印标签！";
            }
            return "";
        }

        private void ctQty_Click(object sender, EventArgs e)
        {
            InputNum input = new InputNum();
            if (input.ShowDialog() != DialogResult.OK)
                return;

            ctQty.Text = input.cResult;
            if (MoDID == -1)
            {
                MessageBox.Show("未找到生产订单号，不能打印！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }
            if (Common.GetInt(input.cResult)<= 0)
            {
                MessageBox.Show("输入的数据小于等于零，不能打印！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }            
            int prnQty=Common.GetInt(SqlAccess.ExecuteScalar("select sum(isnull(num,0)) prnQty from ekk..c_packetstab where modid=" + MoDID , conn));
            int LeftMoQty = Common.GetInt(SqlAccess.ExecuteScalar("select Qty-"+prnQty+" from mom_orderdetail mos where mos.modid=" + MoDID, conn));
           
            if (Common.GetInt(ctQty.Text) > LeftMoQty)
            {
                MessageBox.Show("输入的标签打印数大于当前订单未打印标签数，请检查！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }
            int SetNum = Common.GetInt(SqlAccess.ExecuteScalar(" select eachpacketnum from ekk..c_prodpacketset pset left join inventory inv on pset.cinvccode=inv.cinvccode left join mom_orderdetail mos on inv.cinvcode=mos.invcode where modid=" + tbModid.Text.Trim(), conn));
            if (SetNum > 0)
            {
                int packetnum = Common.GetInt(ctQty.Text) % SetNum > 0 ? Common.GetInt(ctQty.Text) / SetNum + 1 : Common.GetInt(ctQty.Text) / SetNum;
                ctTabqty.Text = packetnum.ToString();
                ctSetnum.Text = SetNum.ToString();
            }
            else
            {
                MessageBox.Show("未设置当前存货分类的半成品包装数量，请在【生产开发】-【生产计划】-【半成品包装设置】中增加设置或填入每包数量！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }
        }

        private void tbColor_Click(object sender, EventArgs e)
        {
            InputNum input = new InputNum();
            if (input.ShowDialog() != DialogResult.OK)
                return;
            tbColor.Text= input.cResult;
        }

        private void ctSetnum_Click(object sender, EventArgs e)
        {
            InputNum input = new InputNum();
            if (input.ShowDialog() != DialogResult.OK)
                return;

            ctSetnum.Text = input.cResult;           
            if (Common.GetInt(input.cResult) <= 0)
            {
                MessageBox.Show("输入的数据小于等于零，不能打印！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return;
            }            
        }

        private void cbAllot_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sheetid = cbAllot.Text;
            StringBuilder sb = new StringBuilder();
            sb.Append(@"SELECT  a.did,a.MoDID,d.mocode 生产订单,b.sortseq 行号,customer.cCusAbbname 客户简称,
                case when charindex('-',e.cinvname)>0 then substring(e.cinvname,charindex('-',e.cinvname)+1,len(e.cinvname)-charindex('-',e.cinvname)) else e.cinvname end  
                  产品名称,e.cInvStd 规格,
                cast(b.Qty as numeric(10,1)) 总计划,a.Qty 数量, b.Invcode 产品编码  
                FROM EKK..C_mateAllots a left join mom_orderdetail b on a.modid=b.modid 
                left join mom_moallocate c on a.allocateid=c.allocateid 
                left join mom_order d on b.moid=d.moid 
                left join inventory e on b.invcode=e.cinvcode 
                left join ekk..c_mateallot g on a.id=g.id
                left join mom_morder h on a.modid=h.modid 
                left join so_sodetails sd on b.orderdid=sd.isosid 
                left join so_somain so on sd.id=so.id left join customer on so.cCuscode=customer.cCuscode
                WHERE g.SheetID='" + sheetid + "' order by 生产订单,行号");
            DataTable dt = SqlAccess.ExecuteSqlDataTable(sb.ToString(), conn);
            BindingSource bs=new BindingSource();
            bs.DataSource=dt;
            dgvAllot.DataSource=bs;
        }

        private void dgvAllot_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            MoDID = Common.GetInt(dgvAllot.Rows[dgvAllot.CurrentCell.RowIndex].Cells["modid1"].Value);
            AllotDID = Common.GetInt(dgvAllot.Rows[dgvAllot.CurrentCell.RowIndex].Cells["id"].Value);
            tbModid.Text = MoDID.ToString();
            GetMoDesc();
        }
    }
}